package main

import (
	"fmt"
	"math/rand"
	"sort"
	"strings"
	"time"
)

func mapTest() {
	// map
	scoreMap := make(map[string]int)
	scoreMap["张三"] = 90
	scoreMap["小明"] = 100
	scoreMap["我来"] = 120
	// map中delete删除
	delete(scoreMap, "小明")
	// map遍历
	for k, v := range scoreMap {
		fmt.Println(k, v)
	}
	// 如果key存在ok为true,v为对应的值；不存在ok为false,v为值类型的零值
	v, ok := scoreMap["王五"]
	if ok {
		fmt.Println(v)
	} else {
		fmt.Println("查无此人")
	}

	// map 按keys进行排序
	rand.Seed(time.Now().UnixNano()) //初始化随机数种子
	var scoreMap2 = make(map[string]int, 200)
	for i := 0; i < 10; i++ {
		key := fmt.Sprintf("stu%02d", i) //生成stu开头的字符串
		value := rand.Intn(100)          //生成0~99的随机整数
		scoreMap2[key] = value
	}
	var keys = make([]string, 0, 200) //取出map中的所有key存入切片keys
	for key := range scoreMap2 {
		keys = append(keys, key)
	}
	sort.Strings(keys)         //对切片进行排序
	for _, key := range keys { //按照排序后的key遍历map
		fmt.Println(key, scoreMap2[key])
	}
	// 练习题：写一个程序，统计一个字符串中每个单词出现的次数。比如：”how do you do”中how=1 do=2 you=1
	_str := "how do you do think you about"
	var wordCount = make(map[string]int, 10)
	words := strings.Split(_str, " ")
	for _, word := range words {
		v, ok = wordCount[word]
		if ok {
			// map中有这个单词
			wordCount[word] = v + 1
		} else {
			wordCount[word] = 1
		}
	}
	for k, v := range wordCount {
		fmt.Println(k, v)
	}
}

func main() {
	mapTest()
}
